#!/usr/bin/env python
# -*- coding: UTF-8 -*-
# @Time : 2021/4/1 21:07 
# @Author : wenzi
# @File : api_cases.py 
# @Software: PyCharm
import json
import time

from apiRestful.extensions import db
from flask import request, jsonify
from flask_restful import Api

from . import api_bp
from apiRestful.utils import log_util
from apiRestful.models.report import Report
from apiRestful.utils.cors_utils import TabrResource
from .api_auth import login_required

api_report = Api(api_bp)
logger = log_util.log


class AddXmlReportApi(TabrResource):

    @login_required
    def post(self):
        logger.debug('AddTextCaseApi.post.url = ' + str(request.url))
        # 如果传入进来的是json数据，那么需要转换成dict类型的数据
        raw_data = request.get_data(as_text=True)
        case_info = json.loads(raw_data)
        logger.debug('AddTextCaseApi.post.case_info = ' + str(case_info))
        if not case_info['caseName']:
            reason = f'{time.strftime("%Y-%m-%d %H:%M:%S")} Case add: Miss require params!'
            return jsonify({'msg': reason})
        else:
            report = Report.query.filter_by(caseName=case_info['caseName']).first()
            if report is None:
                try:
                    c = Report(caseName=case_info['caseName'])
                    c.caseData = case_info['caseData']
                    c.caseType = 'text'
                    c.remark = case_info['remark']
                    db.session.add(c)
                    db.session.commit()
                except:
                    reason = f'{time.strftime("%Y-%m-%d %H:%M:%S")} Case add: {case_info["caseName"]} failure...'
                    db.session.rollback()
                    return jsonify({'msg': reason})
                else:
                    reason = f'{time.strftime("%Y-%m-%d %H:%M:%S")} Case add: {case_info["caseName"]} success...'
                    return jsonify({'msg': reason})
                finally:
                    db.session.close()
            else:
                reason = f'{time.strftime("%Y-%m-%d %H:%M:%S")} Case add: {case_info["caseName"]} failure,because caseName has used....'
                db.session.rollback()
                return jsonify({'msg': reason})


api_report.add_resource(AddXmlReportApi, '/report/xml', endpoint='add_xml_report')